library(arules)
library(arulesViz)
library(car) # función recode
library(ggplot2)
library(reshape)
Examina el contenido de los ficheros
titanic1ytitanic2:
¿En qué formato están almacenados los datos en cada fichero?
Crea dos objetos llamados
titanic.basketytitanic.singleque contengan los datos de los ficheros anteriormente mencionados.
titanic.basket <- read.transactions("data/titanic1", format = "basket",
rm.duplicates = TRUE, quote="\"")
titanic.basket
## transactions in sparse format with
## 1043 transactions (rows) and
## 13 items (columns)
titanic.single <- read.transactions("data/titanic2", format = "single",
cols=c(1,2), rm.duplicates = TRUE, quote="\"")
titanic.single
## transactions in sparse format with
## 1043 transactions (rows) and
## 13 items (columns)
Lee el fichero
titanic.csvy crea undata.framellamadotitanicexamina los atributos que tiene y el tipo de cada uno de ellos.
Leemos el csv indicando que la primera linea contiene los nombres de las columnas.
titanic <- read.csv2('data/titanic.csv', header=TRUE)
str(titanic)
## 'data.frame': 1043 obs. of 6 variables:
## $ clase : Factor w/ 3 levels "primera","segunda",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ superviviente: int 1 1 0 0 0 1 1 0 1 0 ...
## $ sexo : Factor w/ 2 levels "hombre","mujer": 2 1 2 1 2 1 2 1 2 1 ...
## $ edad : num 29 0.917 2 30 25 ...
## $ tarifa : num 211 152 152 152 152 ...
## $ embarque : Factor w/ 3 levels "Cherbourg","Queenstown",..: 3 3 3 3 3 3 3 3 3 1 ...
Tenemos 6 atributos:
factor con tres nivelesentero con valores 0 y 1factor con dos niveles: hombre y mujernumériconuméricofactor con tres nivelesElimina la columna
tarifa, esa información la tenemos discretizada en el atributo clase.
titanic$tarifa <- NULL
Discretiza el atributo
edaden tres categorías: \(Child\) (menor que \(18\)), \(Adult\) (entre \(18\) y \(65\)) y \(Old\) (mayor que \(65\)).
Para discretizar utilizamos los siguientes cortes:
child_until <- 18
adult_until <- 65
titanic$edad <- discretize(titanic$edad, method="fixed", breaks = c(-Inf, child_until, adult_until+1, Inf),
labels=c("child", "adult", "old"), ordered=TRUE)
Recodifica el atributo
supervivientea \(Si\) para el valor \(1\) y \(No\) para el valor \(0\).
titanic$superviviente <- as.factor(recode(titanic$superviviente, "0='NO';1='SI'"))
head(titanic)
Crea un objeto de la clase
transactions, llamadotitanic.trans, a partir deldata.frametitanic.
titanic.trans <- as(titanic, "transactions")
titanic.trans
## transactions in sparse format with
## 1043 transactions (rows) and
## 13 items (columns)
Utilizando la función
write()genera dos ficheros en formatocsvdenominadostitanic.basketytitanic.single, cada uno conteniendo las transacciones en los formatos indicados en su nombre.
write(titanic.trans, "data/titanic.basket", format = "basket")
write(titanic.trans, "data/titanic.single", format = "single")
Partiendo de la base de transacciones
titanic.transobtenida en el ejercicio 2:
Aplica las funciones
apriori()yeclat()y genera los objetostitanic.rulesytitanic.eclatrespectivamente.
titanic.rules <- apriori(titanic.trans)
## Apriori
##
## Parameter specification:
## confidence minval smax arem aval originalSupport maxtime support minlen
## 0.8 0.1 1 none FALSE TRUE 5 0.1 1
## maxlen target ext
## 10 rules FALSE
##
## Algorithmic control:
## filter tree heap memopt load sort verbose
## 0.1 TRUE TRUE FALSE TRUE 2 TRUE
##
## Absolute minimum support count: 104
##
## set item appearances ...[0 item(s)] done [0.00s].
## set transactions ...[13 item(s), 1043 transaction(s)] done [0.00s].
## sorting and recoding items ... [11 item(s)] done [0.00s].
## creating transaction tree ... done [0.00s].
## checking subsets of size 1 2 3 4 5 done [0.00s].
## writing ... [80 rule(s)] done [0.00s].
## creating S4 object ... done [0.00s].
titanic.eclat <- eclat(titanic.trans)
## Eclat
##
## parameter specification:
## tidLists support minlen maxlen target ext
## FALSE 0.1 1 10 frequent itemsets FALSE
##
## algorithmic control:
## sparse sort verbose
## 7 -2 TRUE
##
## Absolute minimum support count: 104
##
## create itemset ...
## set transactions ...[13 item(s), 1043 transaction(s)] done [0.00s].
## sorting and recoding items ... [11 item(s)] done [0.00s].
## creating bit matrix ... [11 row(s), 1043 column(s)] done [0.00s].
## writing ... [87 set(s)] done [0.00s].
## Creating S4 object ... done [0.00s].
Indica cuáles son los valores de los parámetros por defecto.
Apriori:
| confidence | minval | smax | arem | aval | originalSupport | maxtime | support | minlen |
|---|---|---|---|---|---|---|---|---|
| 0.8 | 0.1 | 1 | none | FALSE | TRUE | 5 | 0.1 | 1 |
Eclat:
| tidLists | support | minlen | maxlen | target | ext |
|---|---|---|---|---|---|
| FALSE | 0.1 | 1 | 10 | frequent | itemsets |
Genera una tabla en R en la que en cada fila indique un valor real entre \(0\) y \(1\) (empezando por \(0.1\) y con incrementos de \(0.1\)), el número de reglas generadas para un soporte igual a dicho número en la segunda columna y lo mismo pero para la confianza en la tercera columna. Para poder realizar esta cuestión hay que utilizar la función
length()sobre el conjunto de reglas.
df <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(df) <- c("param_value", "support", "confidence")
r = 1
control_list <- list(verbose = FALSE)
for (i in seq(0.1, 1, 0.1)){
support <- apriori(titanic.trans,
parameter = list(support = i),
control = control_list)
confidence <- apriori(titanic.trans,
parameter = list(confidence = i),
control = control_list)
df[r,] <- c(i, length(support), length(confidence))
r <- r + 1
}
df
Representa gráficamente la tabla anterior.
Como se puede observar, a mayor son los valores de los parámetros support o confidence, menor es la cantidad de reglas que finalmente son generadas.
Genera un conjunto de reglas de asociación para determinar qué items están relacionados con el sexo.
Para ello, solo tenemos que indicar, que en la parte derecha de la regla (rhs) o consecuente, aparezca sexo=hombre o sexo=mujer.
titanic.rules.sexo <- apriori(titanic.trans,
appearance=list(rhs=c("sexo=hombre",
"sexo=mujer"),
default="lhs"),
control = list(verbose = FALSE))
inspect(titanic.rules.sexo)
## lhs rhs support confidence lift count
## [1] {superviviente=NO} => {sexo=hombre} 0.5004794 0.8446602 1.340914 522
## [2] {clase=segunda,
## superviviente=NO} => {sexo=hombre} 0.1294343 0.9246575 1.467911 135
## [3] {superviviente=NO,
## embarque=Southampton} => {sexo=hombre} 0.4074784 0.8483034 1.346698 425
## [4] {superviviente=NO,
## edad=adult} => {sexo=hombre} 0.4439118 0.8621974 1.368755 463
## [5] {clase=segunda,
## superviviente=NO,
## embarque=Southampton} => {sexo=hombre} 0.1169703 0.9172932 1.456220 122
## [6] {clase=segunda,
## superviviente=NO,
## edad=adult} => {sexo=hombre} 0.1236817 0.9214286 1.462785 129
## [7] {clase=tercera,
## superviviente=NO,
## edad=adult} => {sexo=hombre} 0.2310642 0.8033333 1.275307 241
## [8] {superviviente=NO,
## edad=adult,
## embarque=Southampton} => {sexo=hombre} 0.3624161 0.8669725 1.376335 378
## [9] {clase=segunda,
## superviviente=NO,
## edad=adult,
## embarque=Southampton} => {sexo=hombre} 0.1112176 0.9133858 1.450017 116
## [10] {clase=tercera,
## superviviente=NO,
## edad=adult,
## embarque=Southampton} => {sexo=hombre} 0.1965484 0.8200000 1.301766 205
Partiendo del conjunto de reglas generado por el algoritmo
apriorien el ejercicio 4.1:
Selecciona el conjunto de reglas que permitan determinar la supervivencia a partir de la ciudad de embarque ¿Cuántas reglas se han seleccionado?
Algunas de las reglas generadas son:
inspect(head(titanic.rules))
## lhs rhs support confidence
## [1] {} => {edad=adult} 0.8427613 0.8427613
## [2] {embarque=Cherbourg} => {edad=adult} 0.1716203 0.8443396
## [3] {clase=segunda} => {embarque=Southampton} 0.2224353 0.8888889
## [4] {clase=segunda} => {edad=adult} 0.2166826 0.8659004
## [5] {clase=primera} => {edad=adult} 0.2502397 0.9255319
## [6] {sexo=mujer} => {edad=adult} 0.3000959 0.8108808
## lift count
## [1] 1.0000000 879
## [2] 1.0018728 179
## [3] 1.1870821 232
## [4] 1.0274563 226
## [5] 1.0982136 261
## [6] 0.9621715 313
Para seleccionar las que se nos pide, hay que indicar que en el consecuente aparezca el atributo supervivencia y en el antecedente aparezca el atributo embarque. Como en ambos casos, queremos todas aquellas reglas donde por lo menos aparezcan estos atributos, y por ello utilizamos el operador %pin%.
titanic.rules.sub <- subset(titanic.rules, subset =
lhs %pin% "embarque" &
rhs %pin% "superviviente")
inspect(titanic.rules.sub)
## lhs rhs support confidence lift count
## [1] {sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.4074784 0.8220503 1.387376 425
## [2] {clase=segunda,
## sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.1169703 0.8652482 1.460281 122
## [3] {clase=tercera,
## sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.2329818 0.8408304 1.419071 243
## [4] {sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.3624161 0.8494382 1.433599 378
## [5] {clase=segunda,
## sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.1112176 0.9280000 1.566188 116
## [6] {clase=tercera,
## sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.1965484 0.8541667 1.441579 205
Hay un total de \(6\).
Del conjunto anterior, selecciona las reglas con una confianza superior al \(0.83\).
inspect(subset(titanic.rules.sub, subset = confidence > 0.83))
## lhs rhs support confidence lift count
## [1] {clase=segunda,
## sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.1169703 0.8652482 1.460281 122
## [2] {clase=tercera,
## sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.2329818 0.8408304 1.419071 243
## [3] {sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.3624161 0.8494382 1.433599 378
## [4] {clase=segunda,
## sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.1112176 0.9280000 1.566188 116
## [5] {clase=tercera,
## sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.1965484 0.8541667 1.441579 205
De las anteriores, nos quedamos con \(5\) de las \(6\). Si revisamos el ejercicio anterior, podemos ver que verdaderamente solamente una regla no alcanza el \(0.83\) de confianza.
Calcula el índice
gini,hyperliftehyperConfidence. Agrégalos al conjunto de reglastitanic.rulesy muestra por pantalla, para cada índice, las \(5\) reglas que lo tengan más alto.
vector_indices <- c("gini", "hyperLift", "hyperConfidence")
quality(titanic.rules) <- cbind(quality(titanic.rules),
interestMeasure(titanic.rules, vector_indices, titanic.trans))
inspect(head(sort(titanic.rules, by = "gini")))
## lhs rhs support confidence lift count gini hyperLift hyperConfidence
## [1] {superviviente=NO} => {sexo=hombre} 0.5004794 0.8446602 1.340914 522 0.13411633 1.282555 1
## [2] {sexo=hombre,
## edad=adult} => {superviviente=NO} 0.4439118 0.8180212 1.380576 463 0.12067567 1.307910 1
## [3] {superviviente=NO,
## edad=adult} => {sexo=hombre} 0.4439118 0.8621974 1.368755 463 0.11452259 1.300562 1
## [4] {sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.4074784 0.8220503 1.387376 425 0.10356401 1.307692 1
## [5] {sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.3624161 0.8494382 1.433599 378 0.09823658 1.340426 1
## [6] {clase=primera,
## sexo=mujer} => {superviviente=SI} 0.1208054 0.9618321 2.360449 126 0.08828364 1.909091 1
inspect(head(sort(titanic.rules, by = "hyperLift")))
## lhs rhs support confidence lift count gini hyperLift hyperConfidence
## [1] {clase=primera,
## sexo=mujer} => {superviviente=SI} 0.1208054 0.9618321 2.360449 126 0.08828364 1.909091 1
## [2] {clase=primera,
## sexo=mujer,
## edad=adult} => {superviviente=SI} 0.1131352 0.9672131 2.373655 118 0.08300316 1.903226 1
## [3] {clase=segunda,
## sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.1112176 0.9280000 1.566188 116 0.03064972 1.348837 1
## [4] {clase=segunda,
## sexo=hombre,
## edad=adult} => {superviviente=NO} 0.1236817 0.9148936 1.544068 129 0.03249057 1.343750 1
## [5] {sexo=hombre,
## edad=adult,
## embarque=Southampton} => {superviviente=NO} 0.3624161 0.8494382 1.433599 378 0.09823658 1.340426 1
## [6] {sexo=hombre,
## edad=adult} => {superviviente=NO} 0.4439118 0.8180212 1.380576 463 0.12067567 1.307910 1
inspect(head(sort(titanic.rules, by = "hyperConfidence")))
## lhs rhs support confidence lift count gini hyperLift hyperConfidence
## [1] {superviviente=NO} => {sexo=hombre} 0.5004794 0.8446602 1.340914 522 0.13411633 1.282555 1
## [2] {clase=segunda,
## superviviente=NO} => {sexo=hombre} 0.1294343 0.9246575 1.467911 135 0.02828003 1.298077 1
## [3] {clase=primera,
## sexo=mujer} => {superviviente=SI} 0.1208054 0.9618321 2.360449 126 0.08828364 1.909091 1
## [4] {clase=tercera,
## sexo=hombre} => {superviviente=NO} 0.2770853 0.8304598 1.401569 289 0.05669605 1.290179 1
## [5] {superviviente=NO,
## embarque=Southampton} => {sexo=hombre} 0.4074784 0.8483034 1.346698 425 0.08817240 1.272455 1
## [6] {sexo=hombre,
## embarque=Southampton} => {superviviente=NO} 0.4074784 0.8220503 1.387376 425 0.10356401 1.307692 1
Genera diferentes conjuntos de reglas para las reglas no redundantes y maximales.
Conjunto de reglas maximales:
titanic.rules.sub.maximal <- titanic.rules[is.maximal(titanic.rules)]
length(titanic.rules.sub.maximal)
## [1] 15
Conjunto de reglas NO redundantes:
titanic.rules.sub.no_redundant <- titanic.rules[!is.redundant(titanic.rules)]
length(titanic.rules.sub.no_redundant)
## [1] 49
Conjunto de reglas NO redundantes y maximales:
titanic.rules.sub.both <- titanic.rules[is.maximal(titanic.rules) &
!is.redundant(titanic.rules)]
length(titanic.rules.sub.both)
## [1] 6
He generado este ultimo ya que no tenia claro si se pedían los conjuntos de datos con los criterios de forma individual o conjunta.
Genera los conjuntos de los itemsets frecuentes maximales y cerrados.
Conjunto de itemsets maximales:
titanic.eclat.sub.freq <- titanic.eclat[is.maximal(titanic.eclat)]
Conjunto de itemsets cerradas:
titanic.eclat.sub.closed <- titanic.eclat[is.closed(titanic.eclat)]
Conjunto de reglas maximales y cerradas:
titanic.eclat.sub.both <- titanic.eclat[is.maximal(titanic.eclat) &
is.closed(titanic.eclat)]
He generado este ultimo ya que no tenia claro si se pedían los conjuntos de datos con los criterios de forma individual o conjunta.
Partiendo del conjunto de reglas generado por el algoritmo
apriori:
Prueba la versión interactiva de este gráfico.
## To reduce overplotting, jitter is added! Use jitter = 0 to prevent jitter.
Genera un gráfico de dos claves.
Partiendo del conjunto de reglas generado por el algoritmo
apriori:
Representa dichas reglas en una matriz de 3 dimensiones para el soporte.
## Warning in plot.rules(titanic.rules, method = "matrix3D"): method 'matrix3D' is
## deprecated use method 'matrix' with engine '3d'
## Itemsets in Antecedent (LHS)
## [1] "{clase=primera,sexo=mujer,edad=adult}"
## [2] "{clase=primera,sexo=mujer}"
## [3] "{clase=segunda,sexo=hombre,edad=adult,embarque=Southampton}"
## [4] "{clase=segunda,superviviente=NO,edad=adult,embarque=Southampton}"
## [5] "{clase=tercera,sexo=hombre,edad=adult,embarque=Southampton}"
## [6] "{sexo=hombre,edad=adult,embarque=Southampton}"
## [7] "{sexo=hombre,edad=adult}"
## [8] "{superviviente=NO,edad=adult,embarque=Southampton}"
## [9] "{clase=segunda,sexo=hombre,edad=adult}"
## [10] "{clase=segunda,superviviente=NO,edad=adult}"
## [11] "{clase=tercera,superviviente=NO,edad=adult,embarque=Southampton}"
## [12] "{clase=segunda,superviviente=NO,embarque=Southampton}"
## [13] "{clase=segunda,superviviente=NO}"
## [14] "{clase=tercera,sexo=hombre,edad=adult}"
## [15] "{clase=segunda,sexo=hombre,embarque=Southampton}"
## [16] "{clase=segunda,sexo=hombre}"
## [17] "{superviviente=NO,edad=adult}"
## [18] "{sexo=hombre,embarque=Southampton}"
## [19] "{clase=tercera,sexo=hombre,embarque=Southampton}"
## [20] "{clase=segunda,superviviente=NO,sexo=hombre,edad=adult}"
## [21] "{clase=tercera,superviviente=NO,edad=adult}"
## [22] "{clase=segunda,edad=adult}"
## [23] "{superviviente=NO,embarque=Southampton}"
## [24] "{clase=segunda,superviviente=NO,sexo=hombre}"
## [25] "{clase=tercera,sexo=hombre}"
## [26] "{superviviente=NO}"
## [27] "{clase=tercera,superviviente=NO,sexo=hombre,edad=adult}"
## [28] "{clase=segunda,superviviente=NO,sexo=hombre,embarque=Southampton}"
## [29] "{clase=primera,embarque=Cherbourg}"
## [30] "{clase=primera,superviviente=SI,sexo=mujer}"
## [31] "{clase=segunda}"
## [32] "{clase=primera}"
## [33] "{clase=tercera,edad=adult}"
## [34] "{clase=primera,sexo=hombre}"
## [35] "{superviviente=NO,sexo=hombre,edad=adult}"
## [36] "{clase=primera,superviviente=SI}"
## [37] "{clase=primera,embarque=Southampton}"
## [38] "{superviviente=NO,sexo=hombre}"
## [39] "{clase=tercera,superviviente=NO,sexo=hombre}"
## [40] "{superviviente=NO,sexo=hombre,embarque=Southampton}"
## [41] "{clase=tercera,superviviente=NO}"
## [42] "{clase=segunda,embarque=Southampton}"
## [43] "{sexo=hombre}"
## [44] "{embarque=Southampton}"
## [45] "{embarque=Cherbourg}"
## [46] "{clase=tercera,superviviente=NO,sexo=hombre,embarque=Southampton}"
## [47] "{}"
## [48] "{superviviente=SI,sexo=mujer,embarque=Southampton}"
## [49] "{superviviente=SI,sexo=mujer}"
## [50] "{clase=tercera,superviviente=NO,embarque=Southampton}"
## [51] "{superviviente=SI,embarque=Cherbourg}"
## [52] "{sexo=mujer,embarque=Southampton}"
## [53] "{sexo=mujer}"
## [54] "{clase=tercera,embarque=Southampton}"
## [55] "{superviviente=SI}"
## [56] "{superviviente=SI,embarque=Southampton}"
## Itemsets in Consequent (RHS)
## [1] "{edad=adult}" "{embarque=Southampton}" "{sexo=hombre}"
## [4] "{superviviente=NO}" "{superviviente=SI}"
Prueba la versión interactiva.
En 3 dimensiones no funciona la versión interactiva.
Partiendo del conjunto de reglas generado por el algoritmo
apriori:
Genera gráficas para distintos número de grupos.
Prueba la versión interactiva.
# plot(titanic.rules, method = "grouped", control = list(k=30), engine="interactive")
Para las \(10\) reglas con la confianza más alta:
Genera un grafo que las represente.
Prueba la versión interactiva.
Para las \(10\) reglas con el lift más alto:
Genera un gráfico de coordenadas paralelas.
Utilizar la opción
control=list(reorder=TRUE)y compara los resultados.
Reordena el eje Y para que el gráfico sea más legible.
Representa, mediante un gráfico de mosaicos, la regla con el lift más alta que tenga al menos \(3\) items en el antecedentes.